<?php
namespace App\Controllers\Order;
use App\Models\Goods\Goods;
use App\Models\Store\Store;
use App\Models\Order\Order;
use App\Models\Coupons\Coupons;
use App\Models\Coupons\CouponsMy;
use \App\Libs\DB\PailePdo;

/**
*	创建订单
*	错误代码：
	-1 未找到订单
*/
class Corder extends \App\Libs\Base\BaseAction
{
    private static $coupon = '';
    protected function beforeRun() {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }
	
	public function execute(){
		$user = $this->session->user;
		//获取信息
		$goodsId = (int)$this->request->get('goodsId');//商品id
		$ticketId = (int)$this->request->get('ticketId');//优惠券id
		$sum = (int)$this->request->get('sum');//购买数量
		
		//检测商品信息是否正确
		$checkGoodsCode = self::checkGoods( $goodsId , $sum );
		if( empty( $checkGoodsCode->id) ){
			return \App\Libs\Views\Json::view(1, self::errorMessage( $checkGoodsCode ), Null );
		}else{
			$goods = $checkGoodsCode;
		}
		$price =  ( $sum * $goods->sale_price );
		if($price <= 0){
            return \App\Libs\Views\Json::view(1, '体验商品不允许购买', Null );
        }
		//检测优惠券是否正确
		if( !empty( $ticketId ) ){
			$checkTicketCode = self::checkTicket( $ticketId , $user , $goods );
			if( empty( $checkTicketCode->id ) ){
				return \App\Libs\Views\Json::view(1, self::errorMessage( $checkTicketCode ), Null );
			}else{
				$couponsMy = $checkTicketCode;
			}
		}
		//事务开启
		PailePdo::begin();
		//创建订单
		$order = new Order();
		$order->uid = $user->id;
		$order->gid = $goodsId;
		if(isset($couponsMy)){
            $order->price = round($price - (float)self::$coupon->price,2);//金额
            $order->ticket_id = $couponsMy->id;
            $order->ticket_type_id = $couponsMy->cid;
        }else{
            $order->price  = $price;
            $order->ticket_id = 0;
            $order->ticket_type_id = 0;
        }

		$order->sum = $sum;
		$order->order_sn = \App\Libs\Goods\OrderSn::getOrderSn();//订单号
		$order->status = 0;
		$order->ctime = date('Y-m-d H:i:s');
		$order->stime = date("Y-m-d H:i:s",strtotime( \App\Libs\Base\Config::instance()->common['expirationTime'] ));
		$orderResult = $order->save();
//$order->getSqlError($order);
		if( $orderResult == false ){
			PailePdo::rollback();//错误回滚
			return \App\Libs\Views\Json::view(1, '创建订单失败', Null );	
		}else{
			//减库存
			$goods->goods_store -= $sum;
			$goodsSave = $goods->save();
			if( $goodsSave == false ){
				PailePdo::rollback();//错误回滚
			}
			
			//优惠券不为空 改优惠券状态
			if( !empty( $ticketId ) ){
				$couponsMy->status = 1;
				$couponsMySave = $couponsMy->save();
				if( $couponsMySave == false ){
					PailePdo::rollback();//错误回滚
				}
			}
			PailePdo::commit();//正确提交
			//$goods->getSqlError($goods);
			return \App\Libs\Views\Json::view(0, '成功', ['order_sn'=>$order->order_sn,'goods_img'=>$goods->goods_img,'goods_name'=>$goods->goods_name,'price'=>$order->price] );
		}
	}
	
	/**
	*	商品检测
	*/
	private static function checkGoods( $goodsId , $sum ){
		if( empty( $goodsId ) ){
			return -1;
		}
		if( empty( $sum ) ){
			return -2;
		}
		$goods = Goods::find(array(
			'id = :id: and show_status = 2',
			'bind' => array( 'id' => $goodsId )
		));
		//商品不存在
		if( empty( $goods ) ){
			return -1;
		}
		//商品存在
		if( $goods->goods_store < $sum ){
			//库存不足
			return -3;
		}
		return $goods;
	}
	
	/**
	*	优惠券检测
	*/
	private static function checkTicket( $ticketId , $user , $goods ){
		if( empty( $ticketId ) ){
			return -5;
		}
		//查询优惠券是否在当前登录人名下。 并且是未使用及日期未过期状态
		$couponsMy = CouponsMy::find(array(
			'id = :cid: and uid = :uid: and status = 0 and unix_timestamp(end_time) > :time:',
			'bind' => array('cid'=>$ticketId,'uid'=>$user->id,'time'=> time())
		));
		if( empty( $couponsMy ) ){
			return -4;
		}
		//存在优惠券 查询优惠券是否正确
		$coupons = Coupons::find(array(
			'id = :cid:',
			'bind' => array('cid'=>$couponsMy->cid)
		));
		if( empty( $coupons ) ){
			return -5;
		}
		//优惠券是否已过期
		if( date('Y-m-d H:i:s') > $coupons->end_time ){
			return -6;
		}
		
		//检查优惠券类型是否与商品类型一致
		$store = Store::find(array(
			' id = :sid: ',
			'bind'=>array( 'sid'=>$goods->sid )
		));
		if( empty( $store ) ){
			return -7;
		}else{
			//是否为全场通用
			if( $coupons->type != 0 ){
				//不是全场通用 则判断店铺属性与代金券属性是否相同
				if( $store->store_type != $coupons->type ){
					return -8;
				}
			}
		}
		self::$coupon = $coupons;
		return $couponsMy;
	}	
	
	/**
	*	错误信息
	*/
	private static function errorMessage( $key ){
		$errorMessage = array(
			'-1' => '未找到商品或已下架',
			'-2' => '请选择正确的商品数量',
			'-3' => '商品库存不足',
			'-4' => '当前用户不存在此优惠券',
			'-5' => '优惠券不存在',
			'-6' => '优惠券已过期',
			'-7' => '商品所属店铺不存在',
			'-8' => '订单使用优惠券类型与商品类型不符',
		);
		return $errorMessage[$key];
	}
}
